using System;
using System.Collections.Generic;
using System.Linq;

namespace MT5Trade.Models
{
    /// <summary>
    /// 风险度量核心类 - 实现VaR和CVaR计算
    /// 基于严格的统计理论和数学模型，提供科学的风险度量工具
    /// </summary>
    public class RiskMetrics
    {
        #region 常量定义 - 来自知识缓存的参数规格

        // VaR计算参数
        public const double CONFIDENCE_LEVEL_95 = 0.95;
        public const double CONFIDENCE_LEVEL_99 = 0.99;
        public const double CONFIDENCE_LEVEL_999 = 0.999;
        public const double Z_SCORE_95 = 1.65;
        public const double Z_SCORE_99 = 2.33;
        public const double Z_SCORE_999 = 3.09;

        // 止损控制参数
        public const double MIN_STOP_LOSS_RATIO = 0.01; // 最小止损比例1%
        public const double MAX_STOP_LOSS_RATIO = 0.1;  // 最大止损比例10%
        public const double TIME_DECAY_LAMBDA = 0.1;    // 时间衰减参数λ
        public const double TRAILING_STOP_MULTIPLIER = 2.0; // 跟踪止损倍数

        // 数据要求
        public const int MIN_DATA_POINTS = 30;           // 最小数据点数要求
        public const int OPTIMAL_DATA_POINTS = 250;      // 最优数据点数（约1年交易数据）

        #endregion

        #region 私有字段

        private readonly List<double> _historicalReturns;
        private readonly List<double> _historicalPrices;
        private double _currentVolatility;
        private DateTime _lastUpdateTime;
        private readonly IRandomProvider _randomProvider;

        #endregion

        #region 构造函数

        /// <summary>
        /// 初始化风险度量模块
        /// </summary>
        /// <param name="randomProvider">随机数提供器（可选）</param>
        public RiskMetrics(IRandomProvider randomProvider = null)
        {
            _historicalReturns = new List<double>();
            _historicalPrices = new List<double>();
            _currentVolatility = 0.0;
            _lastUpdateTime = DateTime.MinValue;
            
            // 使用提供的随机数生成器或创建确定性生成器
            _randomProvider = randomProvider ?? 
                DeterministicRandomProvider.CreateForOptimization($"RiskMetrics_{DateTime.Today:yyyyMMdd}");
        }

        #endregion

        #region 核心VaR计算方法

        /// <summary>
        /// 计算历史模拟法VaR
        /// 使用完整的历史收益分布，无分布假设
        /// </summary>
        /// <param name="confidenceLevel">置信水平 (0.95 或 0.99)</param>
        /// <param name="positionValue">仓位价值</param>
        /// <returns>VaR值（正值表示潜在损失）</returns>
        public double CalculateHistoricalVaR(double confidenceLevel, double positionValue)
        {
            if (_historicalReturns.Count < MIN_DATA_POINTS)
            {
                throw new InvalidOperationException($"历史数据不足，至少需要{MIN_DATA_POINTS}个数据点，当前仅有{_historicalReturns.Count}个");
            }

            if (confidenceLevel <= 0 || confidenceLevel >= 1)
            {
                throw new ArgumentException("置信水平必须在0和1之间");
            }

            // 将收益率转换为损失（取负值）
            var losses = _historicalReturns.Select(r => -r).OrderBy(l => l).ToList();
            
            // 计算分位数位置
            double position = (1 - confidenceLevel) * losses.Count;
            int lowerIndex = (int)Math.Floor(position);
            int upperIndex = Math.Min(lowerIndex + 1, losses.Count - 1);
            
            // 线性插值计算精确的VaR
            double weight = position - lowerIndex;
            double varQuantile = losses[lowerIndex] * (1 - weight) + losses[upperIndex] * weight;
            
            return Math.Max(varQuantile * positionValue, 0); // 确保VaR为正值
        }

        /// <summary>
        /// 计算参数化VaR（假设正态分布）
        /// 基于均值和标准差的解析解方法
        /// </summary>
        /// <param name="confidenceLevel">置信水平</param>
        /// <param name="positionValue">仓位价值</param>
        /// <returns>参数化VaR值</returns>
        public double CalculateParametricVaR(double confidenceLevel, double positionValue)
        {
            if (_historicalReturns.Count < MIN_DATA_POINTS)
            {
                throw new InvalidOperationException($"数据不足，无法计算参数化VaR");
            }

            // 计算收益率的均值和标准差
            double meanReturn = _historicalReturns.Average();
            double volatility = CalculateVolatility();

            // 获取对应置信水平的Z值
            double zScore = GetZScore(confidenceLevel);

            // 参数化VaR公式：VaR = -(μ - z*σ) * Position_Value
            double var = -(meanReturn - zScore * volatility) * positionValue;

            return Math.Max(var, 0); // 确保VaR为正值
        }

        /// <summary>
        /// 计算条件风险价值（CVaR）
        /// CVaR = E[Loss | Loss ≥ VaR]
        /// </summary>
        /// <param name="confidenceLevel">置信水平</param>
        /// <param name="positionValue">仓位价值</param>
        /// <returns>CVaR值</returns>
        public double CalculateCVaR(double confidenceLevel, double positionValue)
        {
            if (_historicalReturns.Count < MIN_DATA_POINTS)
            {
                throw new InvalidOperationException($"数据不足，无法计算CVaR");
            }

            // 首先计算VaR
            double var = CalculateHistoricalVaR(confidenceLevel, positionValue);
            
            // 将收益率转换为损失
            var losses = _historicalReturns.Select(r => -r * positionValue).ToList();
            
            // 找出超过VaR的损失
            var excessLosses = losses.Where(loss => loss >= var).ToList();
            
            if (excessLosses.Count == 0)
            {
                return var; // 如果没有超过VaR的损失，CVaR等于VaR
            }

            // CVaR是超过VaR的平均损失
            return excessLosses.Average();
        }

        /// <summary>
        /// 计算蒙特卡洛模拟VaR
        /// 基于随机抽样方法验证其他VaR计算结果
        /// </summary>
        /// <param name="confidenceLevel">置信水平</param>
        /// <param name="positionValue">仓位价值</param>
        /// <param name="numSimulations">模拟次数，默认10000次</param>
        /// <returns>蒙特卡洛VaR值</returns>
        public double CalculateMonteCarloVaR(double confidenceLevel, double positionValue, int numSimulations = 10000)
        {
            if (_historicalReturns.Count < MIN_DATA_POINTS)
            {
                throw new InvalidOperationException($"数据不足，无法进行蒙特卡洛模拟");
            }

            if (numSimulations <= 0)
            {
                throw new ArgumentException("模拟次数必须大于0");
            }

            // 计算历史收益率的统计特征
            double meanReturn = _historicalReturns.Average();
            double volatility = CalculateVolatility() / Math.Sqrt(250); // 转换为日波动率
            
            var simulatedLosses = new List<double>();

            // 进行蒙特卡洛模拟
            for (int i = 0; i < numSimulations; i++)
            {
                // 使用确定性随机数生成器生成正态分布随机数
                double z = _randomProvider.NextGaussian(0, 1);
                
                // 生成模拟收益率
                double simulatedReturn = meanReturn + volatility * z;
                
                // 转换为损失（负收益率为损失）
                double simulatedLoss = -simulatedReturn * positionValue;
                simulatedLosses.Add(simulatedLoss);
            }

            // 排序并计算VaR
            simulatedLosses.Sort();
            double position = (1 - confidenceLevel) * simulatedLosses.Count;
            int index = (int)Math.Ceiling(position) - 1;
            index = Math.Max(0, Math.Min(index, simulatedLosses.Count - 1));
            
            return Math.Max(simulatedLosses[index], 0);
        }

        /// <summary>
        /// 计算基于t分布的参数化VaR
        /// 适用于具有厚尾特征的收益率分布
        /// </summary>
        /// <param name="confidenceLevel">置信水平</param>
        /// <param name="positionValue">仓位价值</param>
        /// <param name="degreesOfFreedom">t分布的自由度，默认为样本数-2</param>
        /// <returns>t分布参数化VaR值</returns>
        public double CalculateTDistributionVaR(double confidenceLevel, double positionValue, int? degreesOfFreedom = null)
        {
            if (_historicalReturns.Count < MIN_DATA_POINTS)
            {
                throw new InvalidOperationException($"数据不足，无法计算t分布VaR");
            }

            // 计算收益率的均值和标准差
            double meanReturn = _historicalReturns.Average();
            double volatility = CalculateVolatility();

            // 设置自由度
            int df = degreesOfFreedom ?? Math.Max(3, _historicalReturns.Count - 2);

            // 获取t分布的分位数
            double tValue = GetTDistributionQuantile(1 - confidenceLevel, df);

            // t分布VaR公式：VaR = -(μ + t_α,df * σ * √((df-2)/df)) * Position_Value
            double adjustedVolatility = volatility * Math.Sqrt((double)(df - 2) / df);
            double var = -(meanReturn + tValue * adjustedVolatility) * positionValue;

            return Math.Max(var, 0);
        }

        /// <summary>
        /// 计算综合VaR（多种方法的平均）
        /// 提供更稳健的风险度量
        /// </summary>
        /// <param name="confidenceLevel">置信水平</param>
        /// <param name="positionValue">仓位价值</param>
        /// <returns>综合VaR值</returns>
        public double CalculateCompositeVaR(double confidenceLevel, double positionValue)
        {
            if (_historicalReturns.Count < MIN_DATA_POINTS)
            {
                throw new InvalidOperationException($"数据不足，无法计算综合VaR");
            }

            try
            {
                // 计算各种方法的VaR
                double historicalVaR = CalculateHistoricalVaR(confidenceLevel, positionValue);
                double parametricVaR = CalculateParametricVaR(confidenceLevel, positionValue);
                double monteCarloVaR = CalculateMonteCarloVaR(confidenceLevel, positionValue, 5000); // 减少模拟次数以提高速度
                double tDistVaR = CalculateTDistributionVaR(confidenceLevel, positionValue);

                // 加权平均（历史模拟权重最高，其次是t分布）
                double compositeVaR = (0.4 * historicalVaR + 0.2 * parametricVaR + 0.2 * monteCarloVaR + 0.2 * tDistVaR);
                
                return compositeVaR;
            }
            catch (Exception ex)
            {
                // 如果综合计算失败，回退到历史模拟法
                return CalculateHistoricalVaR(confidenceLevel, positionValue);
            }
        }

        #endregion

        #region 动态止损算法

        /// <summary>
        /// 计算基于VaR的动态止损价格
        /// Stop_Loss = Entry_Price × (1 + VaR₉₅/Account_Equity)
        /// </summary>
        /// <param name="entryPrice">入场价格</param>
        /// <param name="accountEquity">账户净值</param>
        /// <param name="positionValue">仓位价值</param>
        /// <param name="isLong">是否多头仓位</param>
        /// <returns>动态止损价格</returns>
        public double CalculateDynamicStopLoss(double entryPrice, double accountEquity, 
            double positionValue, bool isLong)
        {
            // 计算95%置信水平的VaR
            double var95 = CalculateHistoricalVaR(CONFIDENCE_LEVEL_95, positionValue);
            
            // 动态止损比例
            double stopLossRatio = var95 / accountEquity;
            
            // 限制止损比例在合理范围内
            stopLossRatio = Math.Max(MIN_STOP_LOSS_RATIO, 
                              Math.Min(MAX_STOP_LOSS_RATIO, stopLossRatio));
            
            // 计算止损价格
            if (isLong)
            {
                return entryPrice * (1 - stopLossRatio);
            }
            else
            {
                return entryPrice * (1 + stopLossRatio);
            }
        }

        /// <summary>
        /// 计算时间衰减止损价格
        /// Stop_Loss(t) = Entry_Price × (1 + VaR₉₅ × e^(-λt))
        /// </summary>
        /// <param name="entryPrice">入场价格</param>
        /// <param name="accountEquity">账户净值</param>
        /// <param name="positionValue">仓位价值</param>
        /// <param name="holdingTimeHours">持仓时间（小时）</param>
        /// <param name="isLong">是否多头仓位</param>
        /// <returns>时间衰减止损价格</returns>
        public double CalculateTimeDecayStopLoss(double entryPrice, double accountEquity, 
            double positionValue, double holdingTimeHours, bool isLong)
        {
            // 计算95%置信水平的VaR
            double var95 = CalculateHistoricalVaR(CONFIDENCE_LEVEL_95, positionValue);
            
            // 时间衰减系数
            double timeDecayFactor = Math.Exp(-TIME_DECAY_LAMBDA * holdingTimeHours);
            
            // 动态止损比例（随时间衰减）
            double stopLossRatio = (var95 / accountEquity) * timeDecayFactor;
            
            // 限制止损比例
            stopLossRatio = Math.Max(MIN_STOP_LOSS_RATIO, 
                              Math.Min(MAX_STOP_LOSS_RATIO, stopLossRatio));
            
            // 计算止损价格
            if (isLong)
            {
                return entryPrice * (1 - stopLossRatio);
            }
            else
            {
                return entryPrice * (1 + stopLossRatio);
            }
        }

        /// <summary>
        /// 计算基于ATR的跟踪止损价格
        /// Trailing_Stop = High_Price × (1 - σ × √holding_time)
        /// </summary>
        /// <param name="currentPrice">当前价格</param>
        /// <param name="highestPrice">最高价（多头）或最低价（空头）</param>
        /// <param name="atr">平均真实波幅</param>
        /// <param name="holdingTimeHours">持仓时间（小时）</param>
        /// <param name="isLong">是否多头仓位</param>
        /// <returns>跟踪止损价格</returns>
        public double CalculateTrailingStopLoss(double currentPrice, double highestPrice, 
            double atr, double holdingTimeHours, bool isLong)
        {
            if (atr <= 0)
            {
                throw new ArgumentException("ATR必须大于0");
            }

            // 当前波动率
            double currentVolatility = _currentVolatility > 0 ? _currentVolatility : atr / currentPrice;
            
            // 时间调整系数
            double timeAdjustment = Math.Sqrt(Math.Max(holdingTimeHours / 24.0, 0.1)); // 至少0.1天
            
            // 跟踪止损距离
            double trailingDistance = currentVolatility * TRAILING_STOP_MULTIPLIER * timeAdjustment;
            
            // 限制跟踪距离
            trailingDistance = Math.Max(MIN_STOP_LOSS_RATIO, 
                                 Math.Min(MAX_STOP_LOSS_RATIO, trailingDistance));
            
            // 计算跟踪止损价格
            if (isLong)
            {
                return highestPrice * (1 - trailingDistance);
            }
            else
            {
                return highestPrice * (1 + trailingDistance);
            }
        }

        #endregion

        #region 尾部风险监控

        /// <summary>
        /// 计算VaR突破频率
        /// 监控VaR模型的有效性
        /// </summary>
        /// <param name="actualLosses">实际损失序列</param>
        /// <param name="varPredictions">VaR预测序列</param>
        /// <returns>突破频率（应接近1-置信水平）</returns>
        public double CalculateVaRBreachFrequency(List<double> actualLosses, List<double> varPredictions)
        {
            if (actualLosses.Count != varPredictions.Count)
            {
                throw new ArgumentException("实际损失和VaR预测序列长度不匹配");
            }

            if (actualLosses.Count == 0)
            {
                return 0.0;
            }

            int breaches = 0;
            for (int i = 0; i < actualLosses.Count; i++)
            {
                if (actualLosses[i] > varPredictions[i])
                {
                    breaches++;
                }
            }

            return (double)breaches / actualLosses.Count;
        }

        /// <summary>
        /// 计算CVaR偏差程度
        /// 衡量实际尾部损失与CVaR预测的差异
        /// </summary>
        /// <param name="actualTailLosses">实际尾部损失</param>
        /// <param name="cvarPrediction">CVaR预测值</param>
        /// <returns>相对偏差比例</returns>
        public double CalculateCVaRDeviation(List<double> actualTailLosses, double cvarPrediction)
        {
            if (actualTailLosses.Count == 0)
            {
                return 0.0;
            }

            double actualMeanTailLoss = actualTailLosses.Average();
            
            if (cvarPrediction == 0)
            {
                return actualMeanTailLoss > 0 ? double.PositiveInfinity : 0.0;
            }

            return (actualMeanTailLoss - cvarPrediction) / cvarPrediction;
        }

        /// <summary>
        /// 风险等级评估
        /// 基于当前风险指标评估风险等级
        /// </summary>
        /// <param name="currentVaR">当前VaR</param>
        /// <param name="currentCVaR">当前CVaR</param>
        /// <param name="accountEquity">账户净值</param>
        /// <returns>风险等级字符串</returns>
        public string EvaluateRiskLevel(double currentVaR, double currentCVaR, double accountEquity)
        {
            double varRatio = currentVaR / accountEquity;
            double cvarRatio = currentCVaR / accountEquity;

            if (varRatio <= 0.01 && cvarRatio <= 0.015)
            {
                return "低风险";
            }
            else if (varRatio <= 0.03 && cvarRatio <= 0.045)
            {
                return "中等风险";
            }
            else if (varRatio <= 0.05 && cvarRatio <= 0.075)
            {
                return "较高风险";
            }
            else
            {
                return "高风险";
            }
        }

        #endregion

        #region 数据管理和辅助方法

        /// <summary>
        /// 更新历史数据
        /// </summary>
        /// <param name="prices">价格序列</param>
        public void UpdateHistoricalData(IEnumerable<double> prices)
        {
            var priceList = prices.ToList();
            if (priceList.Count < 2)
            {
                throw new ArgumentException("价格序列至少需要2个数据点");
            }

            _historicalPrices.Clear();
            _historicalPrices.AddRange(priceList);

            // 计算收益率
            _historicalReturns.Clear();
            for (int i = 1; i < _historicalPrices.Count; i++)
            {
                double return_rate = (_historicalPrices[i] - _historicalPrices[i - 1]) / _historicalPrices[i - 1];
                _historicalReturns.Add(return_rate);
            }

            // 更新波动率
            _currentVolatility = CalculateVolatility();
            _lastUpdateTime = DateTime.Now;
        }

        /// <summary>
        /// 添加单个价格数据点
        /// </summary>
        /// <param name="price">新价格</param>
        public void AddPricePoint(double price)
        {
            if (price <= 0)
            {
                throw new ArgumentException("价格必须大于0");
            }

            _historicalPrices.Add(price);

            // 如果有前一个价格，计算收益率
            if (_historicalPrices.Count >= 2)
            {
                int lastIndex = _historicalPrices.Count - 1;
                double return_rate = (_historicalPrices[lastIndex] - _historicalPrices[lastIndex - 1]) / 
                                   _historicalPrices[lastIndex - 1];
                _historicalReturns.Add(return_rate);
            }

            // 限制数据长度，保持最新的数据
            if (_historicalPrices.Count > OPTIMAL_DATA_POINTS)
            {
                _historicalPrices.RemoveRange(0, _historicalPrices.Count - OPTIMAL_DATA_POINTS);
                _historicalReturns.RemoveRange(0, _historicalReturns.Count - (OPTIMAL_DATA_POINTS - 1));
            }

            // 更新波动率
            if (_historicalReturns.Count >= MIN_DATA_POINTS)
            {
                _currentVolatility = CalculateVolatility();
            }

            _lastUpdateTime = DateTime.Now;
        }

        /// <summary>
        /// 计算当前波动率（年化）
        /// </summary>
        /// <returns>年化波动率</returns>
        public double CalculateVolatility()
        {
            if (_historicalReturns.Count < MIN_DATA_POINTS)
            {
                return 0.0;
            }

            double mean = _historicalReturns.Average();
            double sumSquares = _historicalReturns.Sum(r => Math.Pow(r - mean, 2));
            double variance = sumSquares / (_historicalReturns.Count - 1);
            
            // 年化波动率（假设每年250个交易日）
            return Math.Sqrt(variance * 250);
        }

        /// <summary>
        /// 获取对应置信水平的Z分数
        /// </summary>
        /// <param name="confidenceLevel">置信水平</param>
        /// <returns>Z分数</returns>
        private double GetZScore(double confidenceLevel)
        {
            return confidenceLevel switch
            {
                CONFIDENCE_LEVEL_95 => Z_SCORE_95,
                CONFIDENCE_LEVEL_99 => Z_SCORE_99,
                CONFIDENCE_LEVEL_999 => Z_SCORE_999,
                _ => GetZScoreFromNormalDistribution(confidenceLevel)
            };
        }

        /// <summary>
        /// 计算任意置信水平的Z分数（近似）
        /// </summary>
        /// <param name="confidenceLevel">置信水平</param>
        /// <returns>Z分数</returns>
        private double GetZScoreFromNormalDistribution(double confidenceLevel)
        {
            // 使用Beasley-Springer-Moro算法的简化版本
            if (confidenceLevel <= 0 || confidenceLevel >= 1)
            {
                throw new ArgumentException("置信水平必须在0和1之间");
            }

            double p = 1 - confidenceLevel; // 尾部概率
            
            // 简化的正态分布反函数近似
            if (p > 0.5) p = 1 - p;
            
            double t = Math.Sqrt(-2 * Math.Log(p));
            double z = t - ((2.515517 + 0.802853 * t + 0.010328 * t * t) /
                           (1 + 1.432788 * t + 0.189269 * t * t + 0.001308 * t * t * t));
            
            return confidenceLevel > 0.5 ? z : -z;
        }

        /// <summary>
        /// 计算t分布的分位数（简化近似方法）
        /// </summary>
        /// <param name="alpha">尾部概率</param>
        /// <param name="df">自由度</param>
        /// <returns>t分位数</returns>
        private double GetTDistributionQuantile(double alpha, int df)
        {
            if (alpha <= 0 || alpha >= 1)
            {
                throw new ArgumentException("尾部概率必须在0和1之间");
            }

            if (df <= 0)
            {
                throw new ArgumentException("自由度必须大于0");
            }

            // 对于大自由度（>30），t分布近似正态分布
            if (df > 30)
            {
                return GetZScoreFromNormalDistribution(1 - alpha);
            }

            // 使用Cornish-Fisher展开的简化近似
            double z = GetZScoreFromNormalDistribution(1 - alpha);
            
            // t分布的修正项（基于前几阶矩）
            double correction = z / 4.0 * (z * z + 1.0) / df +
                               z / 96.0 * (5.0 * Math.Pow(z, 4) + 16.0 * z * z + 3.0) / (df * df) +
                               z / 384.0 * (3.0 * Math.Pow(z, 6) + 19.0 * Math.Pow(z, 4) + 17.0 * z * z - 15.0) / Math.Pow(df, 3);

            return z + correction;
        }

        #endregion

        #region 状态和诊断方法

        /// <summary>
        /// 获取当前数据状态
        /// </summary>
        /// <returns>数据状态信息</returns>
        public (int PriceCount, int ReturnCount, double Volatility, DateTime LastUpdate) GetDataStatus()
        {
            return (_historicalPrices.Count, _historicalReturns.Count, _currentVolatility, _lastUpdateTime);
        }

        /// <summary>
        /// 检查数据充分性
        /// </summary>
        /// <returns>数据是否充分用于风险计算</returns>
        public bool IsDataSufficient()
        {
            return _historicalReturns.Count >= MIN_DATA_POINTS;
        }

        /// <summary>
        /// 生成风险报告
        /// </summary>
        /// <param name="positionValue">仓位价值</param>
        /// <param name="accountEquity">账户净值</param>
        /// <returns>详细的风险分析报告</returns>
        public string GenerateRiskReport(double positionValue, double accountEquity)
        {
            if (!IsDataSufficient())
            {
                return $"数据不足，无法生成风险报告。当前数据点：{_historicalReturns.Count}，需要至少：{MIN_DATA_POINTS}";
            }

            try
            {
                // 历史模拟法VaR
                double var95 = CalculateHistoricalVaR(CONFIDENCE_LEVEL_95, positionValue);
                double var99 = CalculateHistoricalVaR(CONFIDENCE_LEVEL_99, positionValue);
                double var999 = CalculateHistoricalVaR(CONFIDENCE_LEVEL_999, positionValue);
                
                // 参数化VaR
                double paramVar95 = CalculateParametricVaR(CONFIDENCE_LEVEL_95, positionValue);
                
                // t分布VaR
                double tDistVar95 = CalculateTDistributionVaR(CONFIDENCE_LEVEL_95, positionValue);
                
                // 蒙特卡洛VaR（使用较少模拟次数以提高报告生成速度）
                double mcVar95 = CalculateMonteCarloVaR(CONFIDENCE_LEVEL_95, positionValue, 1000);
                
                // 综合VaR
                double compositeVar95 = CalculateCompositeVaR(CONFIDENCE_LEVEL_95, positionValue);
                
                // CVaR计算
                double cvar95 = CalculateCVaR(CONFIDENCE_LEVEL_95, positionValue);
                double cvar99 = CalculateCVaR(CONFIDENCE_LEVEL_99, positionValue);
                
                string riskLevel = EvaluateRiskLevel(var95, cvar95, accountEquity);

                return $"=== 风险度量报告 ===\n" +
                       $"数据点数量: {_historicalReturns.Count}\n" +
                       $"当前波动率: {_currentVolatility:P2}\n" +
                       $"\n【VaR风险价值】\n" +
                       $"历史模拟VaR(95%): {var95:F2} ({var95/accountEquity:P2})\n" +
                       $"历史模拟VaR(99%): {var99:F2} ({var99/accountEquity:P2})\n" +
                       $"历史模拟VaR(99.9%): {var999:F2} ({var999/accountEquity:P2})\n" +
                       $"参数化VaR(95%): {paramVar95:F2} ({paramVar95/accountEquity:P2})\n" +
                       $"t分布VaR(95%): {tDistVar95:F2} ({tDistVar95/accountEquity:P2})\n" +
                       $"蒙特卡洛VaR(95%): {mcVar95:F2} ({mcVar95/accountEquity:P2})\n" +
                       $"综合VaR(95%): {compositeVar95:F2} ({compositeVar95/accountEquity:P2})\n" +
                       $"\n【CVaR条件风险价值】\n" +
                       $"CVaR(95%): {cvar95:F2} ({cvar95/accountEquity:P2})\n" +
                       $"CVaR(99%): {cvar99:F2} ({cvar99/accountEquity:P2})\n" +
                       $"\n【风险评估】\n" +
                       $"风险等级: {riskLevel}\n" +
                       $"数据更新时间: {_lastUpdateTime:yyyy-MM-dd HH:mm:ss}";
            }
            catch (Exception ex)
            {
                return $"生成风险报告时发生异常: {ex.Message}";
            }
        }

        /// <summary>
        /// 计算夏普比率
        /// Sharpe Ratio = (E[R] - Rf) / σ
        /// 基于现代投资组合理论，衡量风险调整后的收益
        /// </summary>
        /// <param name="returns">历史收益率序列</param>
        /// <param name="riskFreeRate">无风险利率（日化）</param>
        /// <returns>夏普比率</returns>
        public double CalculateSharpeRatio(List<double> returns, double riskFreeRate)
        {
            // 验证输入数据
            if (returns == null || returns.Count < MIN_DATA_POINTS)
            {
                throw new ArgumentException($"计算夏普比率需要至少{MIN_DATA_POINTS}个数据点");
            }

            // 计算平均收益率
            double meanReturn = returns.Average();

            // 计算收益率标准差
            double variance = returns.Sum(r => Math.Pow(r - meanReturn, 2)) / (returns.Count - 1);
            double standardDeviation = Math.Sqrt(variance);

            // 避免除零错误
            if (standardDeviation <= 1e-10)
            {
                return 0.0;
            }

            // 计算夏普比率
            // SR = (Rp - Rf) / σp
            double sharpeRatio = (meanReturn - riskFreeRate) / standardDeviation;

            // 年化夏普比率（假设每年250个交易日）
            double annualizedSharpeRatio = sharpeRatio * Math.Sqrt(250);

            return annualizedSharpeRatio;
        }

        #endregion

        #region 兼容性方法

        /// <summary>
        /// 计算VaR值（兼容性方法，使用历史模拟法）
        /// </summary>
        /// <param name="confidenceLevel">置信水平</param>
        /// <param name="positionValue">仓位价值</param>
        /// <returns>VaR值</returns>
        public double CalculateVaR(double confidenceLevel, double positionValue)
        {
            return CalculateHistoricalVaR(confidenceLevel, positionValue);
        }

        /// <summary>
        /// 兼容性方法：基于收益率数组计算VaR
        /// </summary>
        /// <param name="returns">收益率数组</param>
        /// <param name="confidenceLevel">置信水平</param>
        /// <returns>VaR值</returns>
        public double CalculateVaR(double[] returns, double confidenceLevel)
        {
            if (returns == null || returns.Length == 0)
            {
                return 0;
            }

            // 添加历史收益率数据
            _historicalReturns.Clear();
            _historicalReturns.AddRange(returns);

            // 使用标准仓位大小计算VaR
            return CalculateHistoricalVaR(confidenceLevel, 1.0);
        }

        /// <summary>
        /// 兼容性方法：基于收益率数组计算CVaR
        /// </summary>
        /// <param name="returns">收益率数组</param>
        /// <param name="confidenceLevel">置信水平</param>
        /// <returns>CVaR值</returns>
        public double CalculateCVaR(double[] returns, double confidenceLevel)
        {
            if (returns == null || returns.Length == 0)
            {
                return 0;
            }

            // 添加历史收益率数据
            _historicalReturns.Clear();
            _historicalReturns.AddRange(returns);

            // 使用标准仓位大小计算CVaR
            return CalculateCVaR(confidenceLevel, 1.0);
        }

        #endregion
    }
}

